using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Data.Entity.Validation;
using System.Diagnostics;
using System.Linq;
using System.Linq.Expressions;
using System.Web;

namespace InvoiceProject.Models
{ 
    public class BusinessRepository : IBusinessRepository
    {
        InvoiceProjectContext context = new InvoiceProjectContext();

        public IQueryable<Business> All
        {
            get { return context.Businesses; }
        }

        public IQueryable<Business> AllIncluding(params Expression<Func<Business, object>>[] includeProperties)
        {
            IQueryable<Business> query = context.Businesses;
            foreach (var includeProperty in includeProperties) {
                query = query.Include(includeProperty);
            }
            return query;
        }

        public Business Find(long id)
        {
          
            return context.Businesses.Include("Address").Where(business => business.Id == id).First();
        }

  

        public void InsertOrUpdate(Business business)
        {
           // business.Validate();
            if (business.Id == default(long)) {
                // New entity
                context.Businesses.Add(business);
            } else {
                // Existing entity
                context.Entry(business).State = EntityState.Modified;
            }
        }

        public void Delete(long id)
        {
            var business = context.Businesses.Find(id);
            context.Businesses.Remove(business);
        }

        public void Save()
        {
            context.SaveChanges();

            //   try{ context.SaveChanges();}
            //catch (DbEntityValidationException dbEx)
            //{
            //    foreach (var validationErrors in dbEx.EntityValidationErrors)
            //    {
            //        foreach (var validationError in validationErrors.ValidationErrors)
            //        {
            //            Trace.TraceInformation("Property: {0} Error: {1}", validationError.PropertyName, validationError.ErrorMessage);
            //        }
            //    }
            //}
        }
    }

    public interface IBusinessRepository
    {
        IQueryable<Business> All { get; }
        IQueryable<Business> AllIncluding(params Expression<Func<Business, object>>[] includeProperties);
        Business Find(long id);
        void InsertOrUpdate(Business business);
        void Delete(long id);
        void Save();
       
    }
}